package zheng.mockit.plugin;

import zheng.mockit.compare.IMessageCompare;
import zheng.mockit.compare.DefaultMessageCompare;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by zcz on 16-7-29.
 */
public abstract class AbstractClient extends AbstractPlugin implements IClient {

    protected ExecutorService executor;

    @Override
    public void startup() {
        executor = Executors.newCachedThreadPool();
    }

    @Override
    public void shutdown() {
        executor.shutdown();
        try {
            executor.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendRequest(final Object message) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
                doSendMessage(message);
            }
        });
    }

    protected abstract void doSendMessage(Object message);

    @Override
    public void assertResponse(Object message) {
        assertResponse(message, new DefaultMessageCompare());
    }

    @Override
    public void assertResponse(Object message, IMessageCompare compare) {
        Object inMsg = messageHandler.getMessageFromPlugin();
        compare.compare(message, inMsg);
    }

}
